//
//  SendContentView.m
//  ChatDemo
//
//  Created by 陈石 on 15/5/12.
//  Copyright (c) 2015年 陈石. All rights reserved.
//

#import "SendContentView.h"
#import "Mp3Recorder.h"
#import "ACMacros.h"
#import "ProgressHUD.h"

@interface SendContentView () <UITextViewDelegate, Mp3RecorderDelegate>
{
    BOOL        isbeginVoiceRecord;
    Mp3Recorder *MP3;
    NSInteger   playTime;
    NSTimer     *playTimer;

    UILabel *placeHold;
}
@end

@implementation SendContentView

- (id)initWithSuperVC:(UIViewController *)superVC
{
    self.superVC = superVC;
    CGRect frame = CGRectMake(0, Main_Screen_Height - 40 - 64, Main_Screen_Width, 40);

    self = [super initWithFrame:frame];
    if (self)
    {
        MP3 = [[Mp3Recorder alloc] initWithDelegate:self];
        self.backgroundColor         = [UIColor whiteColor];
        //发送消息
        self.btnSendMessage          = [UIButton buttonWithType:UIButtonTypeCustom];
        self.btnSendMessage.frame    = CGRectMake(Main_Screen_Width - 40, 5, 30, 30);
        self.isAbleToSendTextMessage = NO;
        [self.btnSendMessage setTitle:@"" forState:UIControlStateNormal];
        [self.btnSendMessage setBackgroundImage:[UIImage imageNamed:@"Chat_take_picture"] forState:UIControlStateNormal];
        self.btnSendMessage.titleLabel.font = [UIFont systemFontOfSize:12];
        [self.btnSendMessage addTarget:self action:@selector(sendMessage:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.btnSendMessage];

        //改变状态（语音、文字）
        self.btnChangeVoiceState       = [UIButton buttonWithType:UIButtonTypeCustom];
        self.btnChangeVoiceState.frame = CGRectMake(5, 5, 30, 30);
        isbeginVoiceRecord = NO;
        [self.btnChangeVoiceState setBackgroundImage:[UIImage imageNamed:@"chat_voice_record"] forState:UIControlStateNormal];
        self.btnChangeVoiceState.titleLabel.font = [UIFont systemFontOfSize:12];
        [self.btnChangeVoiceState addTarget:self action:@selector(voiceRecord:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:self.btnChangeVoiceState];

        //语音录入键
        self.btnVoiceRecord        = [UIButton buttonWithType:UIButtonTypeCustom];
        self.btnVoiceRecord.frame  = CGRectMake(70, 5, Main_Screen_Width - 70 * 2, 30);
        self.btnVoiceRecord.hidden = YES;
        [self.btnVoiceRecord setBackgroundImage:[UIImage imageNamed:@"chat_message_back"] forState:UIControlStateNormal];
        [self.btnVoiceRecord setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [self.btnVoiceRecord setTitleColor:[[UIColor lightGrayColor] colorWithAlphaComponent:0.5] forState:UIControlStateHighlighted];
        [self.btnVoiceRecord setTitle:@"Hold to Talk" forState:UIControlStateNormal];
        [self.btnVoiceRecord setTitle:@"Release to Send" forState:UIControlStateHighlighted];
        [self.btnVoiceRecord addTarget:self action:@selector(beginRecordVoice:) forControlEvents:UIControlEventTouchDown];
        [self.btnVoiceRecord addTarget:self action:@selector(endRecordVoice:) forControlEvents:UIControlEventTouchUpInside];
        [self.btnVoiceRecord addTarget:self action:@selector(cancelRecordVoice:) forControlEvents:UIControlEventTouchUpOutside | UIControlEventTouchCancel];
        [self.btnVoiceRecord addTarget:self action:@selector(RemindDragExit:) forControlEvents:UIControlEventTouchDragExit];
        [self.btnVoiceRecord addTarget:self action:@selector(RemindDragEnter:) forControlEvents:UIControlEventTouchDragEnter];
        [self addSubview:self.btnVoiceRecord];

        //输入框
        self.TextViewInput                     = [[UITextView alloc] initWithFrame:CGRectMake(45, 5, Main_Screen_Width - 2 * 45, 30)];
        self.TextViewInput.layer.cornerRadius  = 4;
        self.TextViewInput.layer.masksToBounds = YES;
        self.TextViewInput.delegate            = self;
        self.TextViewInput.layer.borderWidth   = 1;
        self.TextViewInput.layer.borderColor   = [[[UIColor lightGrayColor] colorWithAlphaComponent:0.4] CGColor];
        [self addSubview:self.TextViewInput];

        //输入框的提示语
        placeHold = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 200, 30)];
        placeHold.text      = @"";
        placeHold.textColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.8];
        [self.TextViewInput addSubview:placeHold];

        //分割线
        self.layer.borderWidth = 1;
        self.layer.borderColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.3].CGColor;

        //添加通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidEndEditing:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

#pragma mark - 录音touch事件

- (void)beginRecordVoice:(UIButton *)button
{
    [MP3 startRecord];
    playTime  = 0;
    playTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countVoiceTime) userInfo:nil repeats:YES];
    [ProgressHUD show];
}

- (void)endRecordVoice:(UIButton *)button
{
    if (playTimer)
    {
        [MP3 stopRecord];
        [playTimer invalidate];
        playTimer = nil;
    }
}

- (void)cancelRecordVoice:(UIButton *)button
{
    if (playTimer)
    {
        [MP3 cancelRecord];
        [playTimer invalidate];
        playTimer = nil;
    }
    [ProgressHUD dismissWithError:@"Cancel"];
}

- (void)RemindDragExit:(UIButton *)button
{
    [ProgressHUD changeSubTitle:@"Release to cancel"];
}

- (void)RemindDragEnter:(UIButton *)button
{
    [ProgressHUD changeSubTitle:@"Slide up to cancel"];
}

- (void)countVoiceTime
{
    playTime++;
    if (playTime >= 60)
    {
        [self endRecordVoice:nil];
    }
}

#pragma mark - Mp3RecorderDelegate

//回调录音资料
- (void)endConvertWithData:(NSData *)voiceData
{
    [self.delegate sendAudio:self Message:voiceData time:playTime + 1];
    [ProgressHUD dismissWithSuccess:@"Success"];

    //缓冲消失时间 (最好有block回调消失完成)
    self.btnVoiceRecord.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
    {
        self.btnVoiceRecord.enabled = YES;
    });
}

- (void)failRecord
{
    [ProgressHUD dismissWithSuccess:@"Too short"];

    //缓冲消失时间 (最好有block回调消失完成)
    self.btnVoiceRecord.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
    {
        self.btnVoiceRecord.enabled = YES;
    });
}

//改变输入与录音状态
- (void)voiceRecord:(UIButton *)sender
{
    self.btnVoiceRecord.hidden = !self.btnVoiceRecord.hidden;
    self.TextViewInput.hidden  = !self.TextViewInput.hidden;
    isbeginVoiceRecord = !isbeginVoiceRecord;
    if (isbeginVoiceRecord)
    {
        [self.btnChangeVoiceState setBackgroundImage:[UIImage imageNamed:@"chat_ipunt_message"] forState:UIControlStateNormal];
        [self.TextViewInput resignFirstResponder];
    }
    else
    {
        [self.btnChangeVoiceState setBackgroundImage:[UIImage imageNamed:@"chat_voice_record"] forState:UIControlStateNormal];
        [self.TextViewInput becomeFirstResponder];
    }
}

//发送消息（文字图片）
- (void)sendMessage:(UIButton *)sender
{
    if (self.isAbleToSendTextMessage)
    {
        NSString *resultStr = [self.TextViewInput.text stringByReplacingOccurrencesOfString:@"   " withString:@""];
        [self.delegate sendMessage:self Message:resultStr];
    }
    else
    {
        [self.TextViewInput resignFirstResponder];
        UIAlertController *alertContorller = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *alertCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *alertCamera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            [self addCarema];
        }];
        UIAlertAction *alertLib = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            [self openPicLibrary];
        }];
        [alertContorller addAction:alertCancel];
        [alertContorller addAction:alertCamera];
        [alertContorller addAction:alertLib];
        [self.superVC presentViewController:alertContorller animated:YES completion:nil];
    }
}


#pragma mark - TextViewDelegate

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    placeHold.hidden = self.TextViewInput.text.length > 0;
}

- (void)textViewDidChange:(UITextView *)textView
{
    [self changeSendBtnWithPhoto:textView.text.length > 0 ? NO : YES];
    placeHold.hidden = textView.text.length > 0;
}

- (void)changeSendBtnWithPhoto:(BOOL)isPhoto
{
    self.isAbleToSendTextMessage = !isPhoto;
    [self.btnSendMessage setTitle:isPhoto ? @"" : @"send" forState:UIControlStateNormal];
    self.btnSendMessage.frame = RECT_CHANGE_width(self.btnSendMessage, isPhoto ? 30 : 35);
    UIImage *image = [UIImage imageNamed:isPhoto ? @"Chat_take_picture" : @"chat_send_message"];
    [self.btnSendMessage setBackgroundImage:image forState:UIControlStateNormal];
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    placeHold.hidden = self.TextViewInput.text.length > 0;
}

#pragma mark - Add Picture


- (void)addCarema
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate      = self;
        picker.allowsEditing = YES;
        picker.sourceType    = UIImagePickerControllerSourceTypeCamera;
        [self.superVC presentViewController:picker animated:YES completion:^
        {
        }];
    }
    else
    {
        //如果没有提示用户
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Tip" message:@"Your device don't have camera" delegate:nil cancelButtonTitle:@"Sure" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)openPicLibrary
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate      = self;
        picker.allowsEditing = YES;
        picker.sourceType    = UIImagePickerControllerSourceTypePhotoLibrary;
        [self.superVC presentViewController:picker animated:YES completion:^
        {
        }];
    }
}

- (void)beginConvert
{
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    UIImage *editImage = [info objectForKey:UIImagePickerControllerEditedImage];
    //    NSData *imageData = UIImageJPEGRepresentation(editImage, 0.6);
    //设置image的尺寸
    CGSize  imagesize  = editImage.size;
    imagesize.height = 640;
    imagesize.width  = 640;
    //对图片大小进行压缩--

    editImage = [self imageWithImageSimple:editImage scaledToSize:imagesize];
    [self.superVC dismissViewControllerAnimated:YES completion:^
    {
        [self.delegate sendImage:self Message:editImage];
    }];
}

- (UIImage *)imageWithImageSimple:(UIImage *)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    // Get the new image from the context
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.superVC dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
